package com.easybuilder.core.im.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;


public class IMClientWriteHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("server：" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;

        System.out.println(Thread.currentThread().getName() + " server-msg：" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel nioSocketChannel = ctx.channel();
        // 此处新开辟个线程，如果单线程执行，会一直在while内部循环，接受服务端消息的事件无法执行到
        new Thread(() -> {
            byte[] bytes = new byte[1024];
            try {
                while (true) {
                    System.out.println(Thread.currentThread().getName() + " please input your content：");
                    int len = System.in.read(bytes);
                    String content = new String(bytes, 0, len, "UTF-8");
                    if ("EXIT\n".equals(content.toUpperCase())) {
                        System.out.println("client wile unconnect from remote server >>>>>>>>>>>");
                        nioSocketChannel.close();
                        System.out.println("client connect break!");
                    } else {
                        nioSocketChannel.writeAndFlush(Unpooled.copiedBuffer(bytes, 0, len));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

    }
}
